//
//  String+Extensions.swift
//  EarbudsFunctions
//
//  Created by 李然 on 2024/5/16.
//

import Foundation
import CommonCrypto

extension String {
    public func leftPadding(toLength: Int, withPad character: Character) -> String {
        let newLength = self.count
        if newLength < toLength {
            return String(repeatElement(character, count: toLength - newLength)) + self
        } else {
            return self.substring(from: index(self.startIndex, offsetBy: newLength - toLength))
        }
    }
    
    //3des加解密
    public func threeDESEncryptOrDecrypt(op: Int) -> String? {
        //op传1位加密，0为解密
        //CCOperation（kCCEncrypt）加密 1
        //CCOperation（kCCDecrypt) 解密 0
        
        var ccop = CCOperation()
        let key = "CBCDEFGHIJKLMNOPQRSTUVWX"
        let iv = "20160808"
        // Key
        let keyData: NSData = (key as NSString).data(using: String.Encoding.utf8.rawValue) as NSData? ?? NSData()
        let keyBytes         = UnsafeRawPointer(keyData.bytes)
        
        // 加密或解密的内容
        var data: NSData = NSData()
        if op == 1 {
            ccop = CCOperation(kCCEncrypt)
            data  = (self as NSString).data(using: String.Encoding.utf8.rawValue) as NSData? ?? NSData()
        }
        else {
            ccop = CCOperation(kCCDecrypt)
            //base64 decode
            if let decodeData = NSData(base64Encoded: self, options: NSData.Base64DecodingOptions.ignoreUnknownCharacters){
                data = decodeData
            }
            
        }
        
        let dataLength    = size_t(data.length)
        let dataBytes     = UnsafeRawPointer(data.bytes)
        
        // 返回数据
        let cryptData    = NSMutableData(length: Int(dataLength) + kCCBlockSize3DES)
        let cryptPointer = UnsafeMutableRawPointer(cryptData!.mutableBytes)
        let cryptLength  = size_t(cryptData!.length)
        
        //  可选 的初始化向量
        let viData :NSData = (iv as NSString).data(using: String.Encoding.utf8.rawValue) as NSData? ?? NSData()
        let viDataBytes    = UnsafeRawPointer(viData.bytes)
        
        // 特定的几个参数
        let keyLength              = size_t(kCCKeySize3DES)
        let operation: CCOperation = UInt32(ccop)
        let algoritm:  CCAlgorithm = UInt32(kCCAlgorithm3DES)
        let options:   CCOptions   = UInt32(kCCOptionPKCS7Padding)
        
        var numBytesCrypted :size_t = 0
        
        let cryptStatus = CCCrypt(operation, // 加密还是解密
            algoritm, // 算法类型
            options,  // 密码块的设置选项
            keyBytes, // 秘钥的字节
            keyLength, // 秘钥的长度
            viDataBytes, // 可选初始化向量的字节
            dataBytes, // 加解密内容的字节
            dataLength, // 加解密内容的长度
            cryptPointer, // output data buffer
            cryptLength,  // output data length available
            &numBytesCrypted) // real output data length
        
        if UInt32(cryptStatus) == UInt32(kCCSuccess) {
            cryptData!.length = Int(numBytesCrypted)
            if op == 1  {
                //Base64 encode
                let base64cryptString = cryptData!.base64EncodedString(options: .lineLength64Characters)
                //返回加密的数据
                return base64cryptString
            }
            else {
                let base64cryptString = NSString(data: cryptData! as Data,  encoding: String.Encoding.utf8.rawValue) as String?
                //返回解密的数据
                return base64cryptString
            }
        } else {
            print("Error: \(cryptStatus)")
        }
        return nil
    }
}
